package com.mall.util.distributed.raft;

import com.mall.util.distributed.raft.config.RaftConfig;
import com.mall.util.distributed.raft.lifecycle.Lifecycle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * start one local tcp port
 */
@Slf4j
public class RaftServerBootstrap implements InitializingBean {
    @Autowired
    private Lifecycle lifecycle;

    @Autowired
    private RaftConfig raftConfig;

    /* 表明该结点是否已启动过，避免重复启动结点 */
    public volatile boolean started;

    @Override
    public void afterPropertiesSet() throws Exception {
        if(started) return;

        synchronized (this) {
            if(started) return;

            lifecycle.init(future -> {
                if(future) {
                    log.info("{} start success", raftConfig.getAddress());
                }else {
                    log.info("{} start fail", raftConfig.getAddress());
                }
                started = Boolean.TRUE;
            });
        }

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            lifecycle.shutdown(future -> {
                if(future) {
                    log.info("{} shutdown success", raftConfig.getAddress());
                }else {
                    log.info("{} shutdown fail", raftConfig.getAddress());
                }
            });
        }));
    }
}
